<?php
declare (strict_types = 1);

namespace app\command\logic;

use app\command\logic\BaseLogic;
use think\console\Output;

/**
 * 统计-订单交易数据
 * php think cli stats_transaction --msg='{"days":30}'
 */
class CliStatsTransactionLogic extends BaseLogic implements CliInterface
{

    /**
     * 入口方法
     * {@inheritdoc}
     */
    public function run(Output $output, array $msg): bool
    {
        $insertData = [];
        $date       = isset($msg['date']) ? ($msg['date'] == 'today' ? date('Y-m-d') : $msg['date']) : null;
        if ( ! empty($date)) {
            $insertData[] = self::dataForTransaction($date);
        } else {
            $days = intval($msg['days'] ?? 1);
            for ($i = 1; $i <= $days; $i++) {
                $date = date('Y-m-d', strtotime("-$i days"));
                // echo $date . "\n";exit;
                $insertData[] = self::dataForTransaction($date);
            }
        }
        if ( ! empty($insertData)) {
            \think\facade\Db::table('stats_transaction')
                ->replace()
                ->insertAll($insertData);
        }
        return true;
    }

    private static function dataForTransaction($date)
    {
        $end = $date . ' 23:59:59';

        // 订单状态 0待支付 1待发货 2待收货 3已收货 4已完成 5退款中 6退款成功 7取消 8超时取消 9待退货
        //   `order_type` 1线下直付单 2线上单 3线下单 4供应链',

        $field = [
            // 'count(*) as order_total',
            'COALESCE(SUM(CASE WHEN order_type = 2 THEN 1 ELSE 0 END), 0) AS online_order_count',
            'COALESCE(SUM(CASE WHEN order_type in(1,3) THEN 1 ELSE 0 END), 0) AS offline_order_count',
            'COALESCE(SUM(CASE WHEN order_type = 4 THEN 1 ELSE 0 END), 0) AS supply_order_count',

            'COALESCE(SUM(pay_price), 0) AS order_total_price',
            'COALESCE(SUM(CASE WHEN order_type = 2 THEN pay_price ELSE 0 END), 0) AS online_order_price',
            'COALESCE(SUM(CASE WHEN order_type in(1,3) THEN pay_price ELSE 0 END), 0) AS offline_order_price',
            'COALESCE(SUM(CASE WHEN order_type = 4 THEN pay_price ELSE 0 END), 0) AS supply_order_price',

            'COALESCE(COUNT(DISTINCT CASE WHEN order_type = 2 THEN user_id END), 0) AS online_member_count', // 线上下单人数
            'COALESCE(COUNT(DISTINCT CASE WHEN order_type in(1,3) THEN user_id END), 0) AS offline_member_count', // 线下下单人数
        ];
        $data = \think\facade\Db::table('order')
            ->field($field)
            ->whereBetweenTime('create_at', $date, $end)
        // 0待支付 1待发货 2待收货 3已收货 4已完成 5退款中 6退款成功 7取消 8超时取消 9待退货
            ->whereIn('status', [1, 2, 3, 4, 5, 6, 9])
            ->find();
        // echo \think\facade\Db::table('order')->getlastsql();
        // var_dump($data);exit;
        $data['date'] = $date;

        // 社区下单人数
        $data['community_order_member_count'] = \think\facade\Db::table('community_order')
            ->whereBetweenTime('create_at', $date, $end)
            ->count('distinct user_id');
        $data['community_order_count'] = \think\facade\Db::table('community_order')
            ->whereBetweenTime('create_at', $date, $end)
            ->where('status', 1)
            ->count();
        $data['gift_order_count'] = \think\facade\Db::table('packs_order')
            ->whereBetweenTime('create_at', $date, $end)
            ->whereIn('status', [1, 2, 3])
            ->count();

        $data['community_order_price'] = \think\facade\Db::table('community_order')
            ->whereBetweenTime('create_at', $date, $end)
            ->where('status', 1)
            ->sum('pay_price');

        $data['gift_order_price'] = \think\facade\Db::table('packs_order')
            ->whereBetweenTime('create_at', $date, $end)
            ->whereIn('status', [1, 2, 3])
            ->sum('real_price');

        // 提现金额
        // 0审核中 1成功 2失败
        $data['balance_withdrawal_count'] = \think\facade\Db::table('member_withdraw')
            ->where('status', 1)
            ->whereBetweenTime('create_at', $date, $end)
            ->sum('amount');

        // 退款金额
        // 售后单状态(0进行中 1 已拒绝 2 审核通过  3 已退货 4已取消 5 已完成)
        $data['refund_price'] = \think\facade\Db::table('order_refund')
            ->whereBetweenTime('create_at', $date, $end)
            ->whereIn('status', [2, 3, 5])
            ->sum('refund_money');

        // 1 琅狼积分兑换  2 数字资产兑换  4 贡献值兑换
        $field2 = [
            'COALESCE(SUM(CASE WHEN exchange_type = 1 THEN 1 ELSE 0 END), 0) AS langlang_score_count',
            'COALESCE(SUM(CASE WHEN exchange_type = 2 THEN 1 ELSE 0 END), 0) AS digital_money_count',
            'COALESCE(SUM(CASE WHEN exchange_type = 4 THEN 1 ELSE 0 END), 0) AS gxz_score_count',
            'COALESCE(SUM(CASE WHEN exchange_type = 1 THEN pay_coin ELSE 0 END), 0) AS langlang_score_price',
            'COALESCE(SUM(CASE WHEN exchange_type = 2 THEN pay_coin ELSE 0 END), 0) AS digital_money_price',
            'COALESCE(SUM(CASE WHEN exchange_type = 4 THEN pay_coin ELSE 0 END), 0) AS gxz_score_price',
        ];
        $data2 = \think\facade\Db::table('exchange_order')
            ->field($field2)
            ->whereBetweenTime('create_at', $date, $end)
            ->find();

        // 线下浏览数
        $data['offline_view_count'] = \think\facade\Db::table('member_oplog')
            ->whereIn('api', ['/api/shop/shopDetail?shoptype=1', '/api/shop/shopDetail'])
            ->whereBetweenTime('create_at', $date, $end)
            ->count();
        // 线上浏览数
        $data['online_view_count'] = \think\facade\Db::table('member_oplog')
            ->where('api', '/api/shop/shopDetail?shoptype=2')
            ->whereBetweenTime('create_at', $date, $end)
            ->count();
        // 交易总额 累计社区交易额
        $data['order_total_price'] += $data['community_order_price'];
        // 交易总额 累计礼拜交易额
        $data['order_total_price'] += $data['gift_order_price'];
        $data['order_total'] = 0
             + $data['online_order_count']
             + $data['offline_order_count']
             + $data['supply_order_count']
             + $data['community_order_count']
             + $data['gift_order_count']
             + $data2['langlang_score_count']
             + $data2['digital_money_count']
             + $data2['gxz_score_count'];
        return array_merge($data, $data2);

    }
}
